import React, { useState, useRef, useEffect } from 'react'
import { useBreakpoint } from '@/hooks/useBreakpoint'
import { Skeleton } from 'antd'
import './style.css'

interface LazyImageProps {
  src: string
  alt: string
  mobileSrc?: string
  tabletSrc?: string
  className?: string
  style?: React.CSSProperties
  placeholder?: string
  onLoad?: () => void
  onError?: () => void
}

/**
 * 懒加载响应式图片组件
 * Story 3: Task 9 - 性能优化
 */
const LazyImage: React.FC<LazyImageProps> = ({
  src,
  alt,
  mobileSrc,
  tabletSrc,
  className = '',
  style,
  placeholder = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg"%3E%3C/svg%3E',
  onLoad,
  onError
}) => {
  const [isLoaded, setIsLoaded] = useState(false)
  const [isInView, setIsInView] = useState(false)
  const [hasError, setHasError] = useState(false)
  const imgRef = useRef<HTMLImageElement>(null)
  const breakpoint = useBreakpoint()

  // 获取响应式图片源
  const getImageSrc = () => {
    if (breakpoint === 'mobile' && mobileSrc) return mobileSrc
    if (breakpoint === 'tablet' && tabletSrc) return tabletSrc
    return src
  }

  const imageSrc = getImageSrc()

  // Intersection Observer 懒加载
  useEffect(() => {
    if (!imgRef.current) return

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsInView(true)
          observer.disconnect()
        }
      },
      {
        rootMargin: '50px' // 提前50px开始加载
      }
    )

    observer.observe(imgRef.current)

    return () => observer.disconnect()
  }, [])

  const handleLoad = () => {
    setIsLoaded(true)
    onLoad?.()
  }

  const handleError = () => {
    setHasError(true)
    onError?.()
  }

  return (
    <div
      ref={imgRef}
      className={`lazy-image-wrapper ${className}`}
      style={style}
    >
      {!isLoaded && !hasError && (
        <Skeleton.Image
          active
          className="lazy-image-skeleton"
        />
      )}

      {hasError && (
        <div className="lazy-image-error">
          <span>图片加载失败</span>
        </div>
      )}

      <img
        src={isInView ? imageSrc : placeholder}
        alt={alt}
        className={`lazy-image ${isLoaded ? 'loaded' : ''}`}
        onLoad={handleLoad}
        onError={handleError}
        loading="lazy"
        decoding="async"
      />
    </div>
  )
}

export default LazyImage
